package net.sf.rose.spring;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.sf.rose.jdbc.DB;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.web.util.WebUtils;

/**
 * @author fengjian E-mail: 9110530@qq.com
 * @version 创建时间：2018年6月6日 下午10:53:25 
 * 类说明 ：对所有的后台Action请求作AOP拦截处理，记录请求日志和辅助关闭数据库连接
 */
@Aspect
@Component
public class ControllerAspect {

	private static Logger LOG = Logger.getLogger(ControllerAspect.class);

	/**
	 * 只有在这个包目录下的才会自动处理数据库连接服务
	 */
	@Pointcut("execution(public * com.business.action..*.*(..))")
	public void controllerAction() {
	}

	// 环绕通知,环绕增强，相当于MethodInterceptor
	@Around("controllerAction()")
	public Object arround(ProceedingJoinPoint pjp) throws Throwable {
		// 接收到请求
		Date d1 = new Date();
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		// 记录下请求日志
		StringBuilder sb = new StringBuilder();
		sb.append("\n********************************************\n");
		Object user = WebUtils.getUserBeanCache(request);
		if (user != null) {
			sb.append("User:").append(user.toString()).append('\n');
		}
		sb.append("URL：").append(request.getRequestURL().toString()).append('\n');
		sb.append("HTTP_METHOD：").append(request.getMethod()).append('\n');
		sb.append("IP：").append(request.getRemoteAddr()).append('\n');
		String methodName = pjp.getSignature().getName();
		sb.append("CLASS_METHOD：").append(pjp.getSignature().getDeclaringTypeName() + "." + methodName).append('\n');
		// sb.append("ARGS：").append(Arrays.toString(pjp.getArgs())).append('\n');
		// 给请求参数加入数据库连接池
		Object[] arg = pjp.getArgs();
		Service service = null;
		DB db = null;
		if (requestAttributes != null) {
			for (Object obj : arg) {
				if (obj != null) {
					if (obj instanceof Service) {
						service = (Service) obj;
						if (user != null) {
							service.setUser(user);
						}
					} else if (obj instanceof DB) {
						db = (DB) obj;
						service = new Service();
						if (user != null) {
							service.setUser(user);
						}
						db.setService(service);
					}
				}
			}
		}
		// 执行请求处理
		Object retVal = null;
		try {
			retVal = pjp.proceed(arg);
			if (service != null) {
				service.commit();
			}
		} catch (Exception e) {
			LOG.error("", e);
			PageBean p = new PageBean();
			p.setSuccess(false);
			p.setMessage(e.getMessage());
			retVal = p;
		} finally {
			if (service != null) {
				service.close();
			}
			Date d2 = new Date();
			sb.append("userd time:" + (d2.getTime() - d1.getTime()) + '\n');
			sb.append("********************************************");
			LOG.info(sb.toString());
		}
		return retVal;
	}

}